﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace Music_Application
{
    public partial class MediaForm : Form
    {

        DataTable table = null;
        string pathDataAlbumMusic = "";
        int RowSelected = -1; //bài hát ở hàng RowSelected đã được chơi ở bước trước
        DataGridView gridview;
        string stateMedia;
        public MediaForm()
        {
            //
            //Khoi tao duong dan den album music
            pathDataAlbumMusic = "AlbumMusic.txt";
            //
            //trạng thái Media;
            // 1- AUTOPLAY - TU DONG NHAY BAI
            // 2- STOP AUTOPLAY - CHI HAT MOT BAI XONG DUNG
            // 3 - AUTOPLAY ONE SONG - HAT LAP 1 BAI HAT
            stateMedia = "AUTOPLAY";
            //
            //khởi tạo danh sach bài hát
            //
            KhoiTaoDanhSachBaiHat();
            InitializeComponent();
        }

        private void KhoiTaoDanhSachBaiHat()
        {
            table = new DataTable();
            table.Columns.Add("Stt", typeof(int));
            table.Columns.Add("Tên bài hát", typeof(string));
            table.Columns.Add("URL", typeof(string));
            //tao mot playlist trong window media player
            axWindowMedia.playlistCollection.newPlaylist("MyMusic");
            var playlist = axWindowMedia.playlistCollection.getByName("MyMusic").Item(0);
            try
            {
                using (StreamReader rd = new StreamReader(pathDataAlbumMusic))
                {
                    string line;
                    while ((line = rd.ReadLine()) != null)
                    {
                        string[] musicfile = Directory.GetFiles(line, "*.mp3"); // lấy danh sách bài hát trong thư mục
                        int i = table.Rows.Count + 1;
                        foreach (string file in musicfile)
                        {
                            FileInfo fileinfo = new FileInfo(file);
                            table.Rows.Add(i.ToString(), fileinfo.Name.Substring(0, fileinfo.Name.Length - 4), fileinfo.FullName);
                            ++i;
                           // playlist.appendItem(file);
                        }
                    }
                }
            }
            catch (Exception e)
            {

            }



        }

        public void AddMusicList()
        {
            string urlMusicList = null;
            FolderBrowserDialog dialogfile = new FolderBrowserDialog();
            dialogfile.ShowNewFolderButton = false;
            dialogfile.RootFolder = Environment.SpecialFolder.MyComputer;
            if (dialogfile.ShowDialog() == DialogResult.OK)
            {
                urlMusicList = dialogfile.SelectedPath;
                try
                {
                    using (StreamWriter writter = File.AppendText(pathDataAlbumMusic))
                    {
                        writter.WriteLine(urlMusicList.ToString());
                    };
                }
                catch (Exception e)
                {

                }

                //load lại danh sách bài hát
                KhoiTaoDanhSachBaiHat();
                //
                //Nếu Form Danh sach bài hát đang mở thì load lại form
                //
                Form form = FormIsOpening("SongList");
                if (form != null)
                {
                    form.Dispose();
                    ShowMusicList();
                }
            }

        }


        private Form FormIsOpening(string name)
        {
            FormCollection fc = Application.OpenForms;
            foreach (Form form in fc)
            {
                if (form.Name == name)
                    return form;
            }

            return null;
        }

        public void ShowMusicList()
        {
            //
            //Kiem tra form "danh sach bai hat" da hien thi chua
            //
            if (FormIsOpening("SongList") != null)
                return;
            Form MusiclistForm = new Form();
            MusiclistForm.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            MusiclistForm.AutoSize = true;
            MusiclistForm.Name = "SongList";
            MusiclistForm.Text = "Danh sách bài hát";
            MusiclistForm.Disposed += MusiclistForm_Disposed;
            //để thuôc tính Location có giá trị thì thuộc tính StartPosition phải là Manual
            MusiclistForm.StartPosition = FormStartPosition.Manual;
            MusiclistForm.Location = new Point(this.Bounds.Right + 5, this.Location.Y);
            //
            //GridView
            //
            gridview = new DataGridView();
            gridview.Size = new Size(430, 400);
            gridview.RowHeadersVisible = false;
            gridview.Columns.Add("Stt", "Stt");
            gridview.Columns[0].Width = 30;
            gridview.Columns.Add("TenBaiHat", "Tên bài hát");
            gridview.Columns[1].Width = gridview.Width - 31;
            gridview.Columns.Add("URL", "URL");
            gridview.Columns[2].Visible = false;
            gridview.ScrollBars = ScrollBars.Vertical;
            gridview.AllowUserToAddRows = false;
            //su kien datagridview
            gridview.CellMouseDoubleClick += gridview_CellMouseDoubleClick;
            //chọn hết row khi user click vào cell of row
            gridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //không cho phép chỉnh kích thước hàng và cột
            gridview.AllowUserToResizeColumns = false;
            gridview.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            gridview.AllowUserToResizeRows = false;
            gridview.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            gridview.ReadOnly = true;
            //canh giua cho tieu de
            gridview.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            gridview.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            foreach (DataRow row in table.Rows)
            {
                gridview.Rows.Add(row[0], row[1], row[2]);
            }


            MusiclistForm.Controls.Add(gridview);
            MusiclistForm.Show();
        }

        void MusiclistForm_Disposed(object sender, EventArgs e)
        {
            gridview = null;
        }

        void gridview_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (table != null)
            {
                if (RowSelected != -1)
                    ((DataGridView)sender).Rows[RowSelected].DefaultCellStyle.BackColor = Color.Empty;
                DataRow row = table.Rows[e.RowIndex];
                if (row != null)
                    axWindowMedia.URL = row["URL"].ToString();
                ((DataGridView)sender).Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
                RowSelected = e.RowIndex;
            }

        }


        public void PlayMusic()
        {
            if (axWindowMedia.playState == WMPLib.WMPPlayState.wmppsPaused)
                axWindowMedia.Ctlcontrols.play();
        }
        public void PauseMusic()
        {
            if (axWindowMedia.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
                axWindowMedia.Ctlcontrols.pause();
        }
        public void SetVolume(int value)
        {
            axWindowMedia.settings.volume = value;
            //MessageBox.Show(value.ToString());
        }
        public void PlaySongNumber(int numberofsong)
        {
            if ((gridview == null) || (numberofsong >= Convert.ToInt32(table.Rows.Count)) || (numberofsong < 0)) return;
            if (RowSelected != -1)
                if (gridview.Rows[RowSelected] != null) gridview.Rows[RowSelected].DefaultCellStyle.BackColor = Color.Empty;
            if (table.Rows[numberofsong] != null)
            {
                DataRow row = table.Rows[numberofsong];
                if (row != null)
                {
                    axWindowMedia.URL = row["URL"].ToString();
                }
                gridview.Rows[numberofsong].DefaultCellStyle.BackColor = Color.Blue;
            }
            RowSelected = numberofsong;
        }

        private void speakCommandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CommandLineForm AboutCommandForm = new CommandLineForm();
            AboutCommandForm.ShowDialog();
        }

        public void SetStateMediaAutoPlay(string state)
        {
            stateMedia = state;
        }

        private void axWindowMedia_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (e.newState == 8) // wmppsMediaEnded     = 8
            {
                switch (stateMedia)
                {
                    case "AUTOPLAY":
                        int MusicNext = RowSelected + 1;
                        if (MusicNext >= table.Rows.Count)
                            MusicNext = 0;
                        PlaySongNumber(MusicNext);
                        break;
                    case "STOP AUTOPLAY":
                        break;
                    case "AUTOPLAY ONE SONG":
                        PlaySongNumber(RowSelected);
                        break;
                }
            }
        }
    }
}
